/*
 * light.js
 * 物理量
 */
;
(function (call) {
	var main = {
		baseUrl: CafeJS.CXT,
		mapId: "tjMap",
		playList: null,
		datepicker: null,
		legendpicker: null,
		router: {
			findLitCurrentList: '/glk/stat/findLitCurrentList',
			queryDensity: 'zhfx/light/queryDensity',
			getLatestTime: 'zhfx/light/getNewestTime',
			productcfg: "/business/common/json/product.json",
			dislegendTemplate: "/business/template/dislegend.html"
		},
		init: function () {
			this.initView();
		},
		initView: function () {
			var that = this;
			that.initDatePicker();
			that.getLatestTime();
			$.getJSON(that.router.productcfg, function (cfg) {
				that.initProductList(cfg);
			})
		},
		// 获取最新时间
		getLatestTime: function () {
			var that = this;
			// $.ajax({
			// 	url: this.router.getLatestTime,
			// 	type: 'POST'
			// }).done(function (data) {
			// 	if (data) {
			// 		data = new Date(data);
			// 		data.setMinutes(data.getMinutes() - data.getMinutes() % 10);
			// 		that.datepicker.setVal(data.format('yyyy-MM-dd hh:mm'));
			// 	}
			// })
			let data = new Date();
			
			data.setSeconds(0);
			data.setMinutes(data.getMinutes() - data.getMinutes() % 10 - 10);
			that.datepicker.setVal(data.format('yyyy-MM-dd hh:mm'));
		},
		// 初始化产品列表
		initProductList: function (cfg) {
			var that = this
			var params = {
				container: '.product-content.light',
				data: cfg.light,
				eleClick: function (ele, oldEle, selected) {
					var oldId = oldEle.ele_id; // 上一个选中要素
					var name = ele.ele_name;
					that.clearGridLayer(oldId);
					if (ele.type != 'Distribution') {
						GIS.LayerControll.deleteLayer(that.mapId, ['lightningDensity']);
					}
					var linghtTime = new Date(that.datepicker.getVal()).format('yyyy-MM-dd hh:00');
					if(ele.isZD){
						that.datepicker.setVal(linghtTime);
					}
					var pro = {
						name: '闪电' + name.substring(name.length - 2) + '_' + name,
						time: that.calcStartTime(ele),
						bussitype: 'light',
						ele: ele,
						isGrid: false,
						isSK: true
					}
					if (selected) {
						if (ele.type == 'Distribution') {
							// that.initDislegend('data_view_light', selected);
						}
						that.addLayerManage(pro);
						that.queryEleData(ele, pro.time);
					} else {
						CafeJS.layerManage.removeLayer(pro); // 删除当前要素的图层
						if (ele.type == 'Distribution') {
							CafeJS.ModalBoxHide('data_view_light');
						}
					}
				}
			};
			CafeJS.analysis(params);
			if (new Date(that.datepicker.getVal()).getMinutes() !== 0) {
				that.preventEventByMinute(true);
			} else {
				that.preventEventByMinute(false);
			}
		},
		// 闪电分布图例
		initDislegend: function (id, selected) {
			var that = this;
			if (CafeJS.ModalBoxExist(id)) {
				if (!selected) {
					CafeJS.ModalBoxClose(id);
				} else {
					CafeJS.ModalBoxShow(id);
				}
				return;
			}
			CafeJS.ModalBox({
				id: id,
				container: 'cafe-busis-container',
				title: "图例",
				width: 130,
				height: 190,
				m_bottom: 90,
				m_left: 90,
				url: that.router.dislegendTemplate,
				closed: function () {
					CafeJS.ModalBoxHide(id);
				}
			});
		},
		// 初始化时间控件
		initDatePicker: function () {
			var _this = this;
			this.datepicker = CafeJS.Datepicker({
				appendTo: "#datepicker-light",
				type: 3,
				curDate: _this.latestTime,
				timeInterval: 10,
				autoPush: true,
				call: function () {
					_this.queryMultiEleData();
					if (new Date(_this.datepicker.getVal()).getMinutes() !== 0) {
						_this.preventEventByMinute(true);
					} else {
						_this.preventEventByMinute(false);
					}
					CafeJS.dislegend.initView();
				},
				updateDateCall: function () {
					if (new Date(_this.datepicker.getVal()).getMinutes() !== 0) {
						_this.preventEventByMinute(true);
					} else {
						_this.preventEventByMinute(false);
					}
					CafeJS.dislegend.initView();
				}
			});
			$("#datepicker-light").show();
		},
		//当分为00时，元素不能点击，置灰
		preventEventByMinute: function (flag) {
			$(".product-list span").each(function (index) {
				var eleId = $(this).parent().data().eleid;
				if (eleId == "LB3H" || eleId == "LB12H" || eleId == "LB24H" || eleId == "LD3H" || eleId == "LD12H" || eleId == "LD24H") {
					if (flag) {
						//$(this).parent().addClass("preventEventLi");
						//$(this).addClass("preventEvent");
						//$(this).next().addClass("preventEvent");
						//$(this).parent().removeClass("active");
					} else {
						//$(this).parent().removeClass("preventEventLi");
						//$(this).removeClass("preventEvent");
						//$(this).next().removeClass("preventEvent");
					}
				}
			})
		},
		// 初始化图例
		initLegentpicker: function (ele, appendTo) {
			var that = this;
			var layers = that.getModels(ele);
			var layerIds = [];
			$.each(layers, function (i, m) {
				layerIds.push(m.id);
			});
			CafeJS.Legentpicker({
				appendTo: appendTo,
				gisId: that.mapId,
				layerId: layerIds,
				totalWidth: 400,
				h_legend: 15,
				seq: 'decrease',
				productId: ele.color_id,
				isShowSlider: false
			});
		},
		// 初始化播放列表
		initPlayList: function (pro) {
			var that = this;
			var startTime = pro.time;

			var layers = this.getModels(pro.ele);
			var interval = pro.ele.interval || 60;
			this.playList = CafeJS.Timeline3({
				appendTo: "#a-m-timeline",
				curDate: startTime,
				type: 1,
				pro: pro,
				dateOpt: {
					dateFmt: 'yyyy-MM-dd hh:mm',
					timeInterval: interval
				},
				timeInterval: interval,
				layers: layers,
				gisId: that.mapId,
				call: function (pro) {
					CafeJS.layerManage.updateLayer(pro);
					var ele = pro.ele;
					that.queryEleData(ele, pro.time);
				},
				getPlayData: function (pro, timeArr) {
					var ele = pro.ele;
					that.queryEleData(ele, timeArr);
				}
			});
		},
		// 查询已选择要素
		queryMultiEleData: function () {
			var that = this;
			var pro, time;
			$(".light .product-list li.active").each(function (i, ele) {
				pro = $(ele).data('pro');
				time = that.calcStartTime(pro);
				CafeJS.layerManage.updateLayerTime(time, 'light', null, pro.ele_id);
				that.queryEleData(pro, time);
			});
		},
		queryEleData: function (ele, time) {
			var that = this;
			var type = ele.type;
			if (type == 'Distribution') {
				that.findLitCurrentList(ele, time);
			} else {
				that.queryDensity(ele, time);
			}
		},
		// 查询闪电密度
		queryDensity: function (ele, time) {
			var that = this;
			var element = ele.ele_id;
			if (!element) return;

			if (time.indexOf(',') == -1) {
				time = new Date(time).format('yyyy-MM-dd hh:mm:ss');
			}

			var param = {
				queryTime: time,
				proId: element
			}
			$.ajax({
				url: that.router.queryDensity,
				data: param,
				type: "POST",
				success: function (data) {
					that.clearGridLayer(ele.ele_id);
					if (data.isSuccess && data.data.length > 0) {
						that.drawLight(data.data, ele);
					} else {
						alert("该时间点无闪电密度数据");
					}
				}
			})
		},
		// 查询闪电分布
		findLitCurrentList: function (ele, time) {
			debugger
			var that = this;
			var element = ele.ele_id;
			if (!element) return;
			let end = new Date(new Date(time).getTime()).format('yyyyMMddhhmmss');
			let start = new Date(new Date(new Date(time).getTime()  - ele.count)).format('yyyyMMddhhmmss');
			if (time.indexOf(',') == -1) {
				time = new Date(time).format('yyyyMMddhhmmss');
			}

			var param = {
				start,
				end
			}
			$.ajax({
				url: that.router.findLitCurrentList,
				data: param,
				type: "POST",
				success: function (data) {
					that.clearGridLayer(ele.ele_id);
					if (data.code === 0 && data.data.length) {
						that.drawLight(data.data, ele);
					} else {
						alert("该时间点无闪电分布数据");
					}
				}
			})
		},
		// 绘制闪电
		drawLight: function (data, ele) {
			var typeArr = this.getModels(ele);
			var newData = [];
			var colorObj = CafeJS.Legentconfig().cfg()[ele.color_id] || {};
			for (var i = 0; i < data.length; i++) {
				var sign = Number(data[i].Lit_Current);
				newData.push({ "lat": data[i].Lat, "lon": data[i].Lon, "sign": sign });
			}
            debugger
			GIS.GridShow.showByTypes(this.mapId, typeArr, { "data": newData }, {}, colorObj);
		},
		// 增加产品图层
		addLayerManage: function (pro) {
			var that = this;
			if (CafeJS.layerManage) {
				CafeJS.layerManage.addLayer(pro);
			} else {
				CafeJS.layerManage = CafeJS.LayerManage({
					appendTo: "#c-b-layermanage",
					mapId: that.mapId,
					proInfo: pro,
					call: function (pro) {
						CafeJS[pro.bussitype].initPlayList(pro);
					},
					close: function (pro) {
						CafeJS[pro.bussitype].delLayer(pro);
					}
				})
			}
			if (pro.ele.color_id)
				that.initLegentpicker(pro.ele, '.cafe-layer-item.active');
		},
		// 根据时间间隔获取开始时间
		calcStartTime: function (ele) {
			var time = new Date(this.datepicker.getVal());
			// var time = new Date(this.datepicker.getVal());
			switch (ele.interval) {
				case 60:
					time.setMinutes(0);
					break;
			}
			return time.format('yyyy-MM-dd hh:mm');
		},
		// 删除图层后取消要素选择
		delLayer: function(pro) {
			var eleid = pro.ele.ele_id;
			$(".light .product-list li.active").each(function(){
				if ($(this).data('eleid') == eleid){
					$(this).click();
					return false;
				}
			})
		},
		// 清除格点GIS图层
		clearGridLayer: function (eleid) {
			var layerIds = [];
			GLMap.layerIds.forEach(function (layerId) {
				if (layerId.indexOf('light-layer') != -1 && layerId.lastIndexOf(eleid) != -1) {
					layerIds.push(layerId);
				}
			})
			GIS.LayerControll.deleteLayer(this.mapId, layerIds);
		},
		// 获取要素样式
		getModels: function (ele) {
			var models = [];
			$.each(ele.models.split(","), function (i, m) {
				var layerId = "light-layer-" + m + "-" + ele.ele_id;
				models.push({
					type: m,
					visible: true,
					uv: false,
					wd: false,
					id: layerId
				});
			});
			return models;
		}
	};
	if (typeof call === 'function') {
		CafeJS.light = main;
		call(main);
	}

})(function (main) {
	CafeJS.models(['datepicker', 'legentpicker', 'legentconfig', 'ajax', 'timeLine3'], function () {
		main.init();
	});
});
